package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.SocialUser;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MenberLoginVO;
import com.atguigu.gulimall.member.vo.MenberRegistVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MenberRegistVO vo) {
        MemberEntity entity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();

        //设置默认等级
        entity.setLevelId(levelEntity.getId());


        //检查用户名和手机号是否唯一,为了让controller能感知异常 ，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        //保存手机号已经用户名
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

        entity.setNickname(vo.getUserName());

        //密码进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他的默认信息

        //保存
        baseMapper.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameExistException {
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MenberLoginVO vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(
                new QueryWrapper<MemberEntity>()
                        .eq("username", loginacct)
                        .or()
                        .eq("mobile", loginacct));

        if (memberEntity == null) {
            return null;
        } else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 密码匹配
            boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        MemberEntity entityByUid = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getId()));
        //1.如果之前未登录过，封装社交信息
        if (entityByUid == null) {

            String json = null;
            try {
                Map<String, String> queryAccessToken = new HashMap<>();
                queryAccessToken.put("access_token", socialUser.getAccess_token());

                Map<String, String> queryHeader = new HashMap<>();
                queryHeader.put("Content-Type", "application/json;charset=UTF-8");

                //发送请求
                //https://gitee.com/api/v5/user?access_token={access_token}
                HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", queryHeader, queryAccessToken);


                json = EntityUtils.toString(response1.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }

            entityByUid = new MemberEntity();
            entityByUid.setAccessToken(socialUser.getAccess_token());
            entityByUid.setSocialUid(socialUser.getId());
            entityByUid.setExpiresIn(socialUser.getExpires_in());
            MemberLevelEntity defaultLevel = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
            entityByUid.setLevelId(defaultLevel.getId());

            // 第三方信息
            JSONObject jsonObject = JSON.parseObject(json);
            // 昵称、头像
            String name = jsonObject.getString("name");
            String profile_image_url = jsonObject.getString("avatar_url");
            //这个 service 查询的
            entityByUid.setNickname(name);
            entityByUid.setHeader(profile_image_url);

            this.save(entityByUid);
        } else {
            //2.否则更新令牌等信息并返回
            entityByUid.setAccessToken(socialUser.getAccess_token());
            entityByUid.setSocialUid(socialUser.getId());
            entityByUid.setExpiresIn(socialUser.getExpires_in());
            entityByUid.setHeader(socialUser.getAvatar_url());
            entityByUid.setNickname(socialUser.getName());
        }
        return entityByUid;
    }

}